const db = require('../../database')
const decrypt = require("./decrypt");
const bcrypt = require("bcryptjs");
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    const {oldPass, newPass, mail} = req.body;
    const getNewPass = () => bcrypt.hashSync(decrypt(newPass), 10);

    if (!mail) {
        const username = req.auth.username;
        let sql = 'select password, chance from users where username = ?';
        db.query(sql, username, (err, data) => {
            if (err) return res.cc(err)
            if (data.length === 0) return res.cc('用户不存在')
            let {password, chance} = data[0];
            if (!bcrypt.compareSync(decrypt(oldPass), password)) {
                chance--;
                if (chance === 2) {
                    const nowDate = new Date().toISOString().slice(0, 10);
                    sql = `update users set chance=${chance}, verErrStartDate='${nowDate}' where username='${username}'`;
                } else if (chance === 0) {
                    sql = `update users set chance=${chance}, status=1 where username='${username}'`;
                } else {
                    sql = `update users set chance=${chance} where username='${username}'`;
                }
                db.query(sql, (err, data) => {
                    if (err) writeLogs('err', {err});
                    else if (data.affectedRows === 0) writeLogs('lock', {
                        username,
                        success: false,
                    });
                    else if (chance === 0) {
                        writeLogs('lock', {
                            username,
                            success: true,
                            reason: '连续多次尝试修改密码但验证失败',
                        })
                    }
                })
                return res.cc(chance, 2)
            } else {
                sql = 'update users set password = ? where username = ?'
                db.query(sql, [getNewPass(), username], (err)=>{
                    if (err) return res.cc(err);
                    writeLogs('edit', {
                        username,
                        info: '密码',
                    });
                    res.cc('修改成功', 0);
                })
            }
        })
    } else {
        const sql = 'update users set password = ? where mail = ?'
        db.query(sql, [getNewPass(), mail], (err)=>{
            if (err) return res.cc(err);
            writeLogs('edit', {
                username,
                info: '密码',
            });
            res.cc('修改成功', 0);
        })
    }
}